package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.repository.ApArticleSearchRepository;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.ITemplateService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.minio.MinioClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
@Service
public class TemplateServiceImpl implements ITemplateService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private ApArticleSearchRepository searchRepository;


    @Override
    @Async
    public void createHtml(ApArticle apArticle, String content) {
        try {
            System.out.println(Thread.currentThread().getName()+"生成静态html服务开始执行");
            Template template = configuration.getTemplate("article.ftl");
            Map<String,Object> map=new HashMap<>();
            map.put("content", JSON.parseArray(content));
            //合并模板和数据
            StringWriter out=new StringWriter();
            template.process(map,out);
            //上传静态html文件到minio
            InputStream is=new ByteArrayInputStream(out.toString().getBytes());
            String url = minIOService.upload(apArticle.getId() + ".html", is, "text/html");
            // 将url地址更新到文章表中
            apArticle.setStaticUrl(url);
            apArticleService.updateById(apArticle);


            //将数据同步到es中
            ApArticleSearch apArticleSearch=new ApArticleSearch();
            BeanUtils.copyProperties(apArticle,apArticleSearch);
            searchRepository.save(apArticleSearch);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
